import config from '@/common/config.js'
import routes from './routes.js'

const $u = uni.$u
let oldRequest = $u.http.request
$u.http.request = function (options = {}) {
  // 模拟数据
  let route = getMatchRoute(options)
  if (config.isMock && route) {
    let response = route.response
    let data = null
    let type = typeof response
    let typeStr = Object.prototype.toString.call(response)
    // 字符串
    if (type === 'boolean' || type === 'string' || type === 'number' || typeStr === '[object Object]') {
      data = route.response
    }
    // 函数
    else if (type === 'function') {
      try {
        data = route.response()
      } catch (e) {
        data = ''
      }
    }
    if (data !== null) {
      return Promise.resolve(data)
    }
  }

  return oldRequest.apply($u.http, arguments)
}

// 获取匹配的路由
function getMatchRoute (options) {
  options = options || {}
  let url = options.url
  url = String(url)
  let method = String(options.method || 'get')
  let route = null
  let routers = Array.isArray(routes) ? routes : [routes]
  routers.forEach(item => {
    if (url.indexOf(item.path) > -1 && method.indexOf(item.method || 'get') > -1) {
      route = item
    }
  })

  return route
}